package cn.learn.dubbo3.enhance.processor;

import org.apache.dubbo.config.spring.beans.factory.annotation.AbstractAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.InjectionMetadata;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Desc
 * @Author XieWei
 * @Date 2022/1/26 17:35
 */
public class ServiceRefrenceInjectionMetadata extends InjectionMetadata {
    private Class<?> targetClass;
    private final Collection<ServiceRefrenceFieldElement> fieldElements;


    public ServiceRefrenceInjectionMetadata(Class<?> targetClass, Collection<ServiceRefrenceFieldElement> fieldElements) {
        super(targetClass, combine(fieldElements));
        this.targetClass = targetClass;
        this.fieldElements = fieldElements;
    }

    public Collection<ServiceRefrenceFieldElement> getFieldElements() {
        return fieldElements;
    }

    // since Spring 5.2.4
    @Override
    protected boolean needsRefresh(Class<?> clazz) {
        if (this.targetClass == clazz) {
            return false;
        }
        //IGNORE Spring CGLIB enhanced class
        if (targetClass.isAssignableFrom(clazz) &&  clazz.getName().contains("$$EnhancerBySpringCGLIB$$")) {
            return false;
        }
        return true;
    }

    private static <T> Collection<T> combine(Collection<? extends T>... elements) {
        List<T> allElements = new ArrayList<T>();
        for (Collection<? extends T> e : elements) {
            allElements.addAll(e);
        }
        return allElements;
    }

}
